package it.polito.connectedcar.network;

import java.io.IOException;
import java.net.InetAddress;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class SimulatedNetworkConnector extends EntityNetworkConnector{

	private ScheduledExecutorService executorService;
	private final Random delayRandom = new Random(System.currentTimeMillis());
	public SimulatedNetworkConnector(int port) {
		super(port);
		executorService = Executors.newSingleThreadScheduledExecutor();
	}
	
	@Override
	public void sendMessageTo(final Message message, final InetAddress target,final int port) 
	{
		executorService.schedule(new Runnable() {
			
			@Override
			public void run() {
				/*send the Message to the underlying network service in order to be transmitted*/
				try {
					networkCommunicator.sendMessage(message,target,port);
					
				} catch (IOException e) {
					e.printStackTrace();
				}
				
			}
		}, getSimulatedDelay(), TimeUnit.MILLISECONDS);
		
	}

	/**
	 * This method must simulate the delay in a cellular network for packet transmission
	 * @return
	 */
	private long getSimulatedDelay() {
		
		return delayRandom.nextLong();
	}
}
